package com.yyfax.ph.personal.mymoney.cash;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.yyfax.common.CLog;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.Divider;
import com.yyfax.common.recyclerview.FooterLoadMoreView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.SystemTool;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseFragment;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.adapter.BaseRetryRecyclerAdapter;

import java.util.List;

/**
 * 提现
 * Created by xiongyufeng on 2017/11/11.
 * Copyright  2017 www.yylending.com. All Rights Reserved.
 */
public class DrawDetailFragment extends BaseFragment implements DrawDetailPresenter.View,
		BaseRetryRecyclerAdapter.RetryClickListener, OnRefreshListener, OnLoadMoreListener, DrawDetailAdapter.OnFailClickListener {

	private static final String TAG = DrawDetailFragment.class.getSimpleName();
	private final static int LOADER_ID = 1002;

	@BindView(R.id.recycler_view)
	IRecyclerView mRecyclerView;
	Unbinder unbinder;

	private FooterLoadMoreView mLoadMoreView;

	private DrawDetailAdapter mAdapter;
	private BaseRetryRecyclerAdapter mStatesAdapter;

	private int mPageNum = 1;
	private int mPageSize = 20;
	private boolean mIsRefreshing = false;
	private String startDate = SystemTool.getDataTime("yyyy/MM/01");
	private boolean mIsLoading = false;

	private DrawDetailPresenter mPresenter;

	private CashActivity mActivity;

	public void setStartDate(String date) {
		startDate = date;
		mRecyclerView.post(new Runnable() {
			@Override
			public void run() {
				mRecyclerView.setRefreshing(true);
			}
		});
		onRefresh();
	}

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		if (context instanceof Activity) {
			mActivity = (CashActivity) context;
		}
		getLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (DrawDetailPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(getActivity(), new DrawDetailPresenter.Generator());
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.withdraw_fragment, null);
		unbinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
		mRecyclerView.addItemDecoration(new Divider(DensityUtil.dip2px(getActivity(), 0.5f), YJPH.getInstance().color(R.color.color_efefef), false, 0, 0, 0, 0, 0));
		View noNetworkLayout = getActivity().getLayoutInflater().inflate(R.layout.state_view_no_network, mRecyclerView, false);
		View emptyLayout = getActivity().getLayoutInflater().inflate(R.layout.no_withdraw_layout, mRecyclerView, false);
		mLoadMoreView = (FooterLoadMoreView) mRecyclerView.getLoadMoreFooterView();
		mAdapter = new DrawDetailAdapter();
		mAdapter.setOnFailClickListener(this);
		mStatesAdapter = new BaseRetryRecyclerAdapter(mAdapter, null, emptyLayout, noNetworkLayout);
		mStatesAdapter.setRetryClickListener(this);
		mRecyclerView.setIAdapter(mStatesAdapter);

		mRecyclerView.setOnRefreshListener(this);
		mRecyclerView.setOnLoadMoreListener(this);
		mRecyclerView.post(new Runnable() {
			@Override
			public void run() {
				mRecyclerView.setRefreshing(true);
			}
		});
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}

	@Override
	public void refreshWithDrawDetail(int cnt, int amountSum, List<DrawDetailModel.DrawInfo> list) {
		if (mIsRefreshing) {
			refreshFinish();
			mActivity.setWithDrawInfo(cnt, amountSum);
			if (null != list && list.size() > 0) {
				mStatesAdapter.setState(StatesAdapter.STATE_NORMAL);
				mAdapter.removeAll();
				mAdapter.addData(list);
				mAdapter.notifyDataSetChanged();
				mRecyclerView.scrollToPosition(0);
			} else {
				checkEmpty(false);
			}
		}
		mIsLoading = false;
	}

	@Override
	public void loadMoreWithDrawDetail(int cnt, int amountSum, List<DrawDetailModel.DrawInfo> list) {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (null == list || list.size() == 0) {
			showToast(R.string.has_no_more);
		} else {
			mStatesAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
		}
		mIsLoading = false;
	}

	@Override
	public void getWithDrawFailure(String tips) {
		if (!mIsRefreshing) {
			mPageNum--;
		}
		refreshFinish();
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (mPageNum == 1) {
			checkEmpty(true);
			showToast(R.string.load_failed);
		}
		mIsLoading = false;
	}

	@Override
	public void onLoadMore() {
		if (mIsLoading) {
			return;
		}
		if ((mAdapter.getCount() % mPageSize) == 0) {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.LOADING);
			loadPage(false);
		} else {
			hadNoMore();
		}
		mIsRefreshing = false;
	}

	@Override
	public void onRefresh() {
		if (mIsLoading) {
			return;
		}
		CLog.i(TAG, "onRefresh");
		loadPage(true);
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		mIsRefreshing = true;
	}

	@Override
	public void onRetry() {
		onRefresh();
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mIsLoading = false;
				checkEmpty(true);
			}
		});
	}

	private void loadPage(boolean isRefresh) {
		mIsLoading = true;
		mPageNum = isRefresh ? 1 : ++mPageNum;
		boolean loginSuccess = YJPH.getInstance().getPreferenceManager().isLoginSuccess();
		if (loginSuccess) {
			mPresenter.getWithDrawList(mPageNum, mPageSize, startDate);
		}
	}

	private void refreshFinish() {
		mIsRefreshing = false;
		mRecyclerView.setRefreshing(false);
	}

	private void hadNoMore() {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		showToast(R.string.has_no_more);
	}

	private void checkEmpty(boolean isLoadDataError) {
		refreshFinish();
		if (mPageNum == 1) {
			if (isLoadDataError) {
				mStatesAdapter.setState(StatesAdapter.STATE_ERROR);
			} else {
				mStatesAdapter.setState(StatesAdapter.STATE_EMPTY);
			}
		}
	}

	@Override
	public void onFailItemClick(DrawDetailModel.DrawInfo bean) {
		showTipsDialog(R.string.withdraw_fail_tips);
	}
}